<template>
  <div class="askOff">
    <van-nav-bar
      title="请假申请"
      left-arrow
      @click-left="goBackHandle"
      :fixed="true"
      :border="false"
      :safe-area-inset-top="true"
      style="padding-top: 0px"
    >
    </van-nav-bar>
    <div class="dataContent">
      <div>
        <div class="contentTop"></div>
        <van-form>
          <van-field
            readonly
            clickable
            required
            name="calendar"
            :value="askOffInfo.startTime"
            label="开始时间"
            placeholder="请选择开始时间"
            input-align="right"
            @click="clickShowCalendar(1)"
            :rules="[{ required: true, message: '请选择开始时间' }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <van-field
            readonly
            clickable
            name="calendar"
            required
            :value="askOffInfo.finishTime"
            label="结束时间"
            placeholder="请选择结束时间"
            input-align="right"
            @click="clickShowCalendar(2)"
            :rules="[{ required: true, message: '请选择结束时间' }]"
          >
            <template #extra>
              <van-icon class="extra" name="arrow-down" size="18" />
            </template>
          </van-field>
          <!-- <van-field
            readonly
            clickable
            name="calendar"
            class="askOffTime"
            :value="askOffInfo.askOffLength"
            label="请假时长"
            input-align="right"
          >
            <template #extra>
              <div class="extra" name="extra">天</div>
            </template>
          </van-field> -->
          <van-field
            readonly
            class="askOffTime"
            v-model="askOffInfo.askOffLength"
            label="请假时长"
            input-align="right"
          >
            <template #extra>
              <div class="extra" name="extra">天</div>
            </template>
          </van-field>
          <van-action-sheet
            v-model="showCalendar"
            show-toolbar
            :lock-scroll="false"
            :round="false"
            :lazy-render="false"
            :close-on-click-overlay="true"
            close-on-click-action
            @close="onCancel"
          >
            <van-tabs
              v-model="active"
              :line-width="lineWidth"
              line-height="2px"
              color="#999"
              @click="onClick"
            >
              <van-tab :title="titleTime">
                <van-calendar
                  v-if="checkCalendar === 1"
                  :default-date="defaultDate"
                  :show-confirm="false"
                  :poppable="false"
                  :round="false"
                  :show-title="false"
                  :show-subtitle="false"
                  @select="onSelect"
                  color="#777"
                  row-height="40"
                  :formatter="formatter"
                  :min-date="new Date('2023/01/01')"
                ></van-calendar>
                <van-calendar
                  v-else
                  :default-date="defaultDate"
                  :show-confirm="false"
                  :poppable="false"
                  :round="false"
                  :show-title="false"
                  :show-subtitle="false"
                  @select="onSelect"
                  color="#777"
                  row-height="40"
                  :formatter="formatter1"
                  :min-date="new Date('2023/01/01')"
                ></van-calendar>
              </van-tab>
              <van-tab :title="titleColumns">
                <template
                  ><van-picker
                    ref="mypicker"
                    :columns="columns"
                    @change="onChange"
                    :swipe-duration="100"
                  >
                  </van-picker
                ></template>
                <!-- <van-picker
                  v-else
                  :default-index="selectindex"
                  :columns="columns"
                  @change="onChange"
                /> -->
              </van-tab>
              <template #nav-right>
                <span class="sheetConfirm" @click="sheetConfirm">确认</span>
              </template>
            </van-tabs>
          </van-action-sheet>
          <div class="contentTop"></div>
          <van-field
            v-model="askOffInfo.askOffReason"
            rows="3"
            maxlength="100"
            show-word-limit
            required
            autocomplete="off"
            error-message-align="left"
            type="textarea"
            class="textarea"
            label="请假事由"
            placeholder="请输入请假事由"
            :rules="[{ required: true }]"
          />
          <div class="footer">
            <van-button type="default" @click="submit">提交</van-button>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import { SuccesFN } from '@/DceMessage'
import { Toast } from 'vant'
import { GetLunarDays, SpecialDays } from './dateformat.js'
import backMixin from '@/backMixin'
export default {
  name: 'askOff',
  mixins: [backMixin],
  data() {
    return {
      arrDate: [],
      askOffInfo: {
        startTime: '', //表单开始时间
        finishTime: '', //表单结束时间
        askOffLength: '', //表单请假时长
        askOffReason: '' //表单请假事由
      },
      showCalendar: false, //是否展示日历弹窗
      active: 0, //tab栏默认选中日历
      defaultDate: new Date(), //默认选中日期
      selectindex: null, //默认选中picker第几个
      titleTime: '', //日历标题
      titleColumns: '上午', //默认选中上午
      lineWidth: '90px', //tab栏下横线默认长度
      columns1: [
        //picker选项
        {
          values: ['上午', '下午']
        }
      ],
      columns: [
        //picker选项
        {
          values: ['上午', '下午']
        }
      ],
      // mindate: new Date(), //截止日期最小日期
      checkCalendar: null,
      clickForm: '', //点击的是开始时间还是结束时间
      finishPeriodsTime: null,
      sum: 0,
      starttime: '',
      finishtime: '',
      finishtimesave: '',
      sumarr: [],
      dateall: [], //存储所有区间日期
      datetype: 0, //判断节假日 0：非节假日 1：节假日
      paramsData: {}
    }
  },
  created() {
    if (
      this.$route.params &&
      JSON.parse(window.localStorage.getItem('askOffOrOverTimeData'))
    ) {
      console.log('进入判断')
      this.paramsData = this.$route.params
    }
    console.log(this.paramsData)
    if (this.paramsData && this.paramsData.StartDate) {
      this.askOffInfo.startTime = this.paramsData.StartDate
      this.askOffInfo.finishTime = this.paramsData.EndDate
      this.askOffInfo.askOffLength = this.paramsData.Duration
      this.askOffInfo.askOffReason = this.paramsData.Reason
    }
  },
  mounted() {},
  methods: {
    formatter(day) {
      let d = day.date
      let D = this.askOffInfo.startTime
        ? new Date(
            this.askOffInfo.startTime.substr(
              0,
              this.askOffInfo.startTime.length - 3
            )
          )
        : new Date()
      let dateres = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
      let nowdate = `${D.getFullYear()}-${D.getMonth() + 1}-${D.getDate()}`
      // console.log(dateres)
      // console.log(nowdate)
      // console.log('=============start=============')
      // console.log('formate1', day)
      // console.log('formate', dateres)
      // console.log('==============end============')
      // 周日全天不可选
      let week = day.date.getDay()
      if (week == 0 || week == 6) {
        day.type = SpecialDays(week,dateres) //'disabled'
      } else {
        // if (new Date(dateres).valueOf() > new Date(nowdate).valueOf()) {
        day.type = GetLunarDays(dateres)
        // console.log('getLunar(dateres)', GetLunarDays(dateres))
        // }
      }

      return day
    },
    formatter1(day) {
      let d = day.date
      // console.log(
      //   '测试',
      //   this.askOffInfo.finishTime.substr(
      //     0,
      //     this.askOffInfo.finishTime.length - 3
      //   )
      // )
      let D = this.askOffInfo.finishTime
        ? new Date(
            this.askOffInfo.finishTime.substr(
              0,
              this.askOffInfo.finishTime.length - 3
            )
          )
        : new Date()
      let dateres = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`
      let nowdate = `${D.getFullYear()}-${D.getMonth() + 1}-${D.getDate()}`
      // console.log('=============start=============')
      // console.log('formate1', day)
      // console.log('formate', dateres)
      // console.log('==============end============')
      // 周日全天不可选
      let week = day.date.getDay()
      if (week == 0 || week == 6) {
        day.type = SpecialDays(week,dateres) //'disabled'
      } else {
        // if (new Date(dateres).valueOf() > new Date(nowdate).valueOf()) {
        day.type = GetLunarDays(dateres)
        // console.log('getLunar(dateres)', GetLunarDays(dateres))
        // }
      }

      return day
    },
    // tab栏点击事件
    onClick() {
      if (this.active == 0) {
        console.log('000')
        this.lineWidth = '90px'
      } else {
        console.log('111')

        this.lineWidth = '30px'
        setTimeout(() => {
          this.$refs.mypicker.setColumnIndex(0, this.selectindex)
        }, 50)
      }
    },
    // 点击表单显示弹窗
    clickShowCalendar(val) {
      this.checkCalendar = val
      if (val === 1 || this.askOffInfo.startTime) {
        this.showCalendar = true
      }

      if (this.checkCalendar === 2) {
        if (this.askOffInfo.startTime === '') {
          this.showCalendar = false
          Toast.fail('请先选择开始时间')
          return
        }
        if (
          this.askOffInfo.startTime.includes(this.titleTime) &&
          this.askOffInfo.startTime.includes('下午')
        ) {
          this.columns = [
            //picker选项
            {
              values: ['下午']
            }
          ]
          this.titleColumns = '下午'
          this.selectindex = 0
        } else {
          this.columns = [
            //picker选项
            {
              values: ['上午', '下午']
            }
          ]
          if (this.askOffInfo.finishTime === '') {
            this.titleColumns = '上午'
            this.selectindex = 0
          } else {
            if (this.askOffInfo.finishTime.includes('下午')) {
              this.titleColumns = '下午'
              this.selectindex = 1
            } else {
              this.titleColumns = '上午'
              this.selectindex = 0
            }
          }
        }
      } else {
        this.columns = [
          //picker选项
          {
            values: ['上午', '下午']
          }
        ]

        if (this.askOffInfo.startTime.includes('下午')) {
          this.selectindex = 1
        } else {
          this.selectindex = 0
        }
      }

      this.active = 0
      this.lineWidth = '90px'
      let date = new Date()
      let year = date.getFullYear() //获取完整的年份(4位,1970-????)
      let month = date.getMonth() + 1
      month < 10 ? (month = '0' + month) : month
      let strDate = date.getDate()
      strDate < 10 ? (strDate = '0' + strDate) : strDate
      // let strDay = date.getDay()
      // let weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      // this.mindate = new Date(
      //   this.askOffInfo.startTime.substr(
      //     0,
      //     this.askOffInfo.startTime.length - 3
      //   )
      // )
      if (val == 1 && this.askOffInfo.startTime) {
        this.titleTime = this.askOffInfo.startTime.substr(
          0,
          this.askOffInfo.startTime.length - 3
        )
        this.titleColumns = this.askOffInfo.startTime.slice(
          this.askOffInfo.startTime.length - 2,
          this.askOffInfo.startTime.length
        )
        this.defaultDate = new Date(
          this.askOffInfo.startTime.substr(
            0,
            this.askOffInfo.startTime.length - 3
          )
        )
      } else if (val == 2 && this.askOffInfo.finishTime) {
        this.titleTime = this.askOffInfo.finishTime.substr(
          0,
          this.askOffInfo.finishTime.length - 3
        )
        this.titleColumns = this.askOffInfo.finishTime.slice(
          this.askOffInfo.finishTime.length - 2,
          this.askOffInfo.finishTime.length
        )
        this.defaultDate = new Date(
          this.askOffInfo.finishTime.substr(
            0,
            this.askOffInfo.finishTime.length - 3
          )
        )
      } else {
        this.titleTime = this.askOffInfo.startTime
          ? this.askOffInfo.startTime.substr(
              0,
              this.askOffInfo.startTime.length - 3
            )
          : year + '-' + month + '-' + strDate

        this.defaultDate = new Date()
        if (val == 2 && this.askOffInfo.finishTime === '') {
          this.askOffInfo.finishTime = this.askOffInfo.startTime
          this.defaultDate = new Date(
            this.askOffInfo.finishTime.substr(
              0,
              this.askOffInfo.finishTime.length - 3
            )
          )
        }
      }
      if (val == 1) {
        // 点击的是开始时间表单项
        this.clickForm = 1
      } else {
        // 点击的是结束时间表单项
        this.clickForm = 2
      }
    },
    // 选中日期，继续选择上午下午
    onSelect(date) {
      console.log('选中', date)

      let year = date.getFullYear()
      let month = date.getMonth() + 1
      month < 10 ? (month = '0' + month) : month
      let strDate = date.getDate()
      strDate < 10 ? (strDate = '0' + strDate) : strDate
      // let strDay = date.getDay()
      // let weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      this.titleTime = year + '-' + month + '-' + strDate
      this.showCalendar = true
      this.active = 1
      this.lineWidth = '40px'
      //判断截止日期与起始日期是否是同一天并且是下午，若是下午截止日期从下午开始
      if (this.checkCalendar === 2) {
        if (
          this.askOffInfo.startTime.includes(this.titleTime) &&
          this.askOffInfo.startTime.includes('下午')
        ) {
          this.columns = [
            //picker选项
            {
              values: ['下午']
            }
          ]
          this.titleColumns = '下午'
          this.selectindex = 0
        } else {
          this.columns = [
            //picker选项
            {
              values: ['上午', '下午']
            }
          ]
          if (this.askOffInfo.finishTime === '') {
            this.titleColumns = '上午'
            this.selectindex = 0
          } else {
            if (this.askOffInfo.finishTime.includes('下午')) {
              this.titleColumns = '下午'
              this.selectindex = 1
            } else {
              this.titleColumns = '上午'
              this.selectindex = 0
            }
          }
        }
      } else {
        this.columns = [
          //picker选项
          {
            values: ['上午', '下午']
          }
        ]

        if (this.askOffInfo.startTime.includes('下午')) {
          this.selectindex = 1
        } else {
          this.selectindex = 0
        }
      }
      this.$refs.mypicker.setColumnIndex(0, this.selectindex)
    },
    // 选择上午下午change事件
    onChange(picker, value) {
      console.log('切换', picker, value[0])
      // picker.setColumnValues(1, value[0])
      this.titleColumns = value[0]
      console.log('titleColumns>>>>', this.titleColumns)
    },
    //取消弹窗并且
    onCancel() {
      this.askOffInfo.finishTime = this.finishtimesave
    },
    // 点击弹窗的确认按钮
    sheetConfirm() {
      // 弹窗关闭
      setTimeout(() => {
        this.showCalendar = false
      }, 100)

      if (this.clickForm == 1) {
        this.askOffInfo.startTime = this.titleTime + ' ' + this.titleColumns
        this.starttime = this.titleTime
        this.askOffInfo.finishTime = ''
        this.finishtime = ''
        this.finishtimesave = ''
        this.askOffInfo.askOffLength = null
      } else if (this.clickForm == 2) {
        this.askOffInfo.finishTime = this.titleTime + ' ' + this.titleColumns
        this.finishtime = this.titleTime
        this.finishtimesave = this.titleTime + ' ' + this.titleColumns
      }

      // 如果开始时间和结束时间都有值，得到加班时长
      if (this.askOffInfo.finishTime && this.askOffInfo.startTime) {
        let finishTimeTime =
          new Date(
            this.askOffInfo.finishTime.substr(
              0,
              this.askOffInfo.finishTime.length - 3
            )
          ).getTime() /
          (1000 * 3600 * 24)
        let startTimeTime =
          new Date(
            this.askOffInfo.startTime.substr(
              0,
              this.askOffInfo.startTime.length - 3
            )
          ).getTime() /
          (1000 * 3600 * 24)
        let finishPeriods = this.askOffInfo.finishTime.slice(
          this.askOffInfo.finishTime.length - 2,
          this.askOffInfo.finishTime.length
        )
        let startPeriods = this.askOffInfo.startTime.slice(
          this.askOffInfo.startTime.length - 2,
          this.askOffInfo.startTime.length
        )
        let timeTime = finishTimeTime - startTimeTime

        if (timeTime > 0) {
          if (startPeriods == '上午' && finishPeriods == '上午') {
            this.finishPeriodsTime = 0.5
          }
          if (startPeriods == '下午' && finishPeriods == '上午') {
            this.finishPeriodsTime = 0.5
          }
          if (startPeriods == '上午' && finishPeriods == '下午') {
            this.finishPeriodsTime = 1
          }
          if (startPeriods == '下午' && finishPeriods == '下午') {
            this.finishPeriodsTime = 0.5
          }
        }

        /* 计算请假时长 */
        this.getYearAndMonthAndDay(this.starttime, this.finishtime)

        setTimeout(() => {
          this.sum = this.sumarr.length

          // console.log(
          //   '结果呀',
          //   this.finishPeriodsTime,
          //   this.sum,
          //   this.dateall,
          //   this.datetype
          // )
          let askOffLength = this.day(startPeriods, finishPeriods)
          askOffLength = askOffLength - this.sum
          if (askOffLength > 0) {
            this.askOffInfo.askOffLength = askOffLength
          } else {
            this.askOffInfo.askOffLength = ''
          }
          setTimeout(() => {
            this.datetype = 0
            askOffLength = 0
            this.sum = 0
          }, 100)
        }, 500)
      }
    },
    //返回日期区间总天数
    day(startDateFrom, endDateTo) {
      if (this.starttime == '' && this.finishtime == '') {
        return '自动计算/最小单位0.5天'
      } else {
        var sdate = new Date(this.starttime)
        var now = new Date(this.finishtime)
        var days = now.getTime() - sdate.getTime()
        var day = parseInt(days / (1000 * 60 * 60 * 24))
        // console.log(day)
        if (
          now == sdate ||
          (startDateFrom == '上午' && endDateTo == '上午') ||
          (startDateFrom == '下午' && endDateTo == '下午')
        ) {
          day = day + 0.5
        } else if (startDateFrom == '上午' && endDateTo == '下午') {
          day = day + 1
        }
        // console.log('天数》》》》》', day)
        return day
      }
    },
    //获取起止日期区间所有日期，并且计算出含非工作日数量
    getYearAndMonthAndDay(start, end) {
      var date_all = [],
        i = 0
      var startTime = new Date(start)
      var endTime = new Date(end)
      while (endTime.getTime() - startTime.getTime() >= 0) {
        var year = startTime.getFullYear()
        var month =
          (startTime.getMonth() + 1).toString().length == 1
            ? '0' + (startTime.getMonth() + 1).toString()
            : (startTime.getMonth() + 1).toString()
        var day =
          startTime.getDate().toString().length == 1
            ? '0' + startTime.getDate()
            : startTime.getDate()
        date_all[i] = year + '-' + month + '-' + day
        startTime.setDate(startTime.getDate() + 1)
        i += 1
      }
      // console.log('日期区间', date_all)
      this.sumarr = []
      this.dateall = []
      if (
        this.askOffInfo.startTime < this.askOffInfo.finishTime ||
        this.askOffInfo.startTime == this.askOffInfo.finishTime
      ) {
        this.$axios({
          url: `/attendance-api/isholiday`,
          method: 'post',
          data: {
            dateList: date_all.toString()
          }
        }).then(res => {
          if (res) {
            this.dateall = res.data.Object
            // console.log('节假日', res)

            this.sumarr = this.dateall.filter(item => item.IsHoliday == true)
            // console.log('循环结果', this.sumarr)
          }
        })
      }
    },
    // 点击提交按钮
    submit() {
      // console.log('点击提交按钮')
      // console.log(this.askOffInfo)
      let noon = this.askOffInfo.startTime.includes('上午')
        ? this.askOffInfo.startTime.replace('上午', '08:30:00')
        : this.askOffInfo.startTime.replace('下午', '13:30:00')
      let after = this.askOffInfo.finishTime.includes('上午')
        ? this.askOffInfo.finishTime.replace('上午', '12:00:00')
        : this.askOffInfo.finishTime.replace('下午', '17:00:00')
      // console.log('上午结果', noon)
      if (noon !== '' && after !== '' && this.askOffInfo.askOffReason !== '') {
        this.$axios({
          url: '/attendance-api/application-add',
          method: 'POST',
          data: {
            applicantId: JSON.parse(localStorage.getItem('attendance-records'))
              .id,
            deptId: JSON.parse(localStorage.getItem('attendance-records'))
              .deptId,
            startDate: noon,
            endDate: after,
            reason: this.askOffInfo.askOffReason,
            duration: this.askOffInfo.askOffLength,
            type: '0',
            applicationType: '2'
          }
        }).then(res => {
          if (res) {
            SuccesFN(res.data.Message)
            localStorage.setItem('isRefresh', 1)
            if (
              this.paramsData !== {} &&
              JSON.parse(window.localStorage.getItem('askOffOrOverTimeData'))
            ) {
              this.cheXiao()
            }
            localStorage.removeItem('askOffOrOverTimeData')
            // 重新提交成功同时要撤销操作

            setTimeout(() => {
              this.$router.replace('/workbench')
            }, 1000)
          }
        })
      }
    },
    cheXiao() {
      this.$axios({
        url: '/attendance-api/application-cancel',
        method: 'POST',
        data: {
          applicationId: this.paramsData.Id,
          status: 3
        }
      }).then(res => {})
    },
    // 点击返回按钮
    goBackHandle() {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.askOff ::v-deep {
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;

  .van-nav-bar__arrow {
    font-size: 18px;
    color: #000;
  }
  .van-nav-bar__content {
    .van-nav-bar__title {
      font-size: 18px;
    }
  }
  .dataContent {
    // background-color: #f5f5f5;
    .contentTop:first-child {
      margin-top: 56px;
    }
    .van-field {
      padding: 10px 16px;
      // background-color: #f5f5f5;
      // border-bottom: 1px solid #ccc;
    }

    .overTime::after {
      border: 0 !important;
    }
    .textarea {
      display: inline-block;
      .van-field__control--right {
        text-align: left;
      }
    }
    .textarea::after {
      border: 0 !important;
    }
  }
  input.van-field__control::-webkit-input-placeholder {
    color: #c8c9cc;
  }
  .van-field__error-message {
    text-align: right;
  }
  .van-icon {
    padding-top: 3px;
  }
  .extra {
    margin-left: 5px;
  }
  .van-tab {
    font-size: 16px;
  }
  .van-tabs__line {
    transition-duration: 0s !important;
  }
  .van-tabs__wrap {
    position: sticky;
    top: 0;
    // border-bottom: 1px solid #f5f5f5;
    z-index: 998;
  }
  .van-tabs__nav {
    background-color: #eee;
  }
  .sheetConfirm {
    line-height: 44px;
    padding: 0 10px;
    // margin-left: 40px;
    color: #006dff;
  }
  .van-calendar {
    height: 300px;
  }
  .van-picker {
    height: 300px;
  }
  .van-calendar__header {
    position: sticky;
    top: 43px;
    // margin-top: -1px;
    background-color: #fff;
    -webkit-appearance: none;
    box-shadow: 0;
    -webkit-box-shadow: 0;
    z-index: 997;
  }
  .van-action-sheet {
    display: flex;
    // width: 100%;
    justify-content: space-between;
    .van-tabs__nav {
      // width: 80%;
    }
    .button {
      display: inline-block;
      // width: 20%;
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    display: flex;
    width: 100%;
    .van-button {
      flex: 1;
      margin: 10px 16px;
      background-color: #006dff;
      color: #fff;
      font-size: 16px;
      border-radius: 10px;
      border: 0;
    }
  }
}
</style>
